package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.Friendship;
import com.gxnu.edu.cn.ttxxt.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static java.lang.Long.parseLong;

@RestController
@RequestMapping("/api/friends")
public class FriendController {

    @Autowired
    private FriendService friendService;

    @PostMapping("/requests")
    public ResponseEntity<?> sendFriendRequest(@RequestBody Map<String, Object> request) {
        Long senderId = parseLong(request.get("senderId").toString());
        Long receiverId = parseLong(request.get("receiverId").toString());
        String message = String.valueOf(request.get("message"));

        friendService.sendFriendRequest(senderId, receiverId, message);
        return ResponseEntity.ok("好友请求已发送");
    }

    @PostMapping("/requests/{requestId}/accept")
    public ResponseEntity<?> acceptFriendRequest(@PathVariable Long requestId) {
        // 处理接受好友请求的逻辑
        return ResponseEntity.ok("已接受好友请求");
    }

    @PostMapping("/requests/{requestId}/reject")
    public ResponseEntity<?> rejectFriendRequest(@PathVariable Long requestId) {
        // 处理拒绝好友请求的逻辑
        return ResponseEntity.ok("已拒绝好友请求");
    }

    @DeleteMapping("/{friendId}")
    public ResponseEntity<?> deleteFriend(@PathVariable Long friendId,
                                          @RequestBody Map<String, Object> requestBody) {
        // 从请求体中获取userId
        Long userId = ((Integer) requestBody.get("userId")).longValue();

        // 处理删除好友的逻辑
        friendService.deleteFriend(friendId, userId);
        return ResponseEntity.ok("已删除好友");
    }

    @GetMapping("/list")
    public ResponseEntity<?> getFriends(@RequestParam Long userId) {
        System.out.println("收到获取好友列表请求，用户ID: " + userId);
        List<Friendship> friends = friendService.getFriends(userId);
        System.out.println("返回好友数量: " + (friends != null ? friends.size() : 0));
        return ResponseEntity.ok(friends);
    }

    @PutMapping("/{friendId}/remark")
    public ResponseEntity<?> updateFriendRemark(@PathVariable Long friendId, @RequestBody Map<String, String> request) {
        String remark = request.get("remark");
        // 处理更新好友备注的逻辑
        return ResponseEntity.ok("好友备注已更新");
    }

    @PutMapping("/{friendId}/group")
    public ResponseEntity<?> updateFriendGroup(@PathVariable Long friendId, @RequestBody Map<String, String> request) {
        String groupName = request.get("groupName");
        // 处理更新好友分组的逻辑
        return ResponseEntity.ok("好友分组已更新");
    }
}
    